// 属性类型
type propName = string | number | symbol
// 调度中心类型
type eventType = {
  [name: propName]: Function[]
}

interface busType {
  // 发布
  emit(name: propName, args?: Array<any>):void
  // 订阅
  on(name: propName, callbackk: Function):number
  // 取消订阅
  off(name: propName, index?: number):void
}

class eventBus implements busType {
  // 事件调度中心
  eventController: eventType
  constructor() {
    this.eventController = {}
  }
  // ...args: 接收任意个参数
  emit(name: propName, ...args: Array<any>) {
    if (!this.eventController[name]) return
    this.eventController[name].forEach(callback => {
      callback.apply(this, args)
    })
  }
  on(name: propName, callback: Function) {
    if (!this.eventController[name]) {
      // 还没有当前事件，初始化赋值
      this.eventController[name] = []
    }
    this.eventController[name].push(callback)
    // console.log('执行了')
    // 返回当前监听事件在数组当中的索引
    return this.eventController[name].length - 1
  }
  off(name?: propName, index?: number) {
    if (name === undefined) {
      // 移除所有事件
      this.eventController = {}
    } else if (index === undefined) {
      // 移除所有指定名称的事件
      this.eventController[name] = []
    } else {
      // 移除指定事件
      this.eventController[name].splice(index, 1)
    }
  }
}

export default new eventBus()